import { Data, Version, Plugin_Name } from './index.js'
import puppeteer from '../../../lib/puppeteer/puppeteer.js'
import fs from 'fs'
const _path = process.cwd()

/**
 * 渲染HTML模板为图片
 * @param {string} path - 模板路径，格式为"app/tpl"
 * @param {Object} params - 渲染参数
 * @param {Object} [cfg={}] - 配置选项，可选
 * @returns {Promise<*>} - 返回图片对象，可直接用于发送
 */
export default async function (path, params, cfg = {}) {
  let [app, tpl] = path.split('/')
  let layoutPath = process.cwd() + `/plugins/${Plugin_Name}/resources/common/layout/`
  let resPath = `../../../../../plugins/${Plugin_Name}/resources/`
  Data.createDir(`data/html/${Plugin_Name}/${app}/${tpl}`, 'root')
  let data = {
    ...params,
    _plugin: Plugin_Name,
    saveId: params.saveId || params.save_id || tpl,
    tplFile: `./plugins/${Plugin_Name}/resources/${app}/${tpl}.html`,
    pluResPath: resPath,
    _res_path: resPath,
    _layout_path: layoutPath,
    _tpl_path: process.cwd() + `/plugins/${Plugin_Name}/resources/common/tpl/`,
    defaultLayout: layoutPath + 'default.html',
    elemLayout: layoutPath + 'elem.html',
    pageGotoParams: {
      waitUntil: 'networkidle0'
    },
    sys: {
      scale: `style=transform:scale(${cfg.scale || 1})`,
	    copyright: `欢迎加QQ交流群：315239849<br>Yunzai-Bot<span class="version">${Version.yunzai}</span> & 鸢尾花插件<span class="version">${Version.ver}</span>`
    },
    quality: 100
  }
  
  // debug模式下保存渲染数据
  if (process.argv.includes('web-debug')) {
    let saveDir = _path + '/data/ViewData/'
    if (!fs.existsSync(saveDir)) {
      fs.mkdirSync(saveDir)
    }
    let file = saveDir + tpl + '.json'
    data._app = app
    fs.writeFileSync(file, JSON.stringify(data))
  }
  
  // 渲染图像并返回
  let img = await puppeteer.screenshot(`${Plugin_Name}/${app}/${tpl}`, data)
  
  // 如果图像不是标准格式，转换为image对象
  if (img && img?.type != 'image') {
    img = segment.image(img)
  }
  
  return img
}